<template>
  <div id="container"></div>
</template>
<script lang="ts" setup>
import {onMounted, ref, Ref, watch, watchEffect, unref} from 'vue';
import {basicProps} from './props';
import {useWebSocket} from '@vueuse/core';
import {useUserStore} from '/@/store/modules/user';
import {Area} from '@antv/g2plot';
import {useRoute} from 'vue-router'

defineProps({
  ...basicProps,
});

interface dataItem {
  time: string;
  count: number;
}

const visitCountData = ref<dataItem[]>([])


onMounted(() => {
// ws部分
  const userStore = useUserStore();
  const token = userStore.getToken
  let server = ""
  if (window.location.hostname === 'localhost') {
    server = `ws://localhost:8000/ws/${token}`
  } else {
    const host = window.location.origin.replace(/https?:/, 'ws:')
    server = `${host}/ws/${token}`
  }
  console.log(server);
  const {status, data, close, open} = useWebSocket(server, {
    autoReconnect: true,
    heartbeat: true,
    immediate: true
  });
  // watch(status, (newValue, oldValue) => {
  //   if (newValue != 'OPEN') {
  //     setTimeout(() => {
  //       open()
  //     }, 3000)
  //   }
  // })
  watch(data, (newValue, oldValue) => {
        console.log('data', oldValue, '->', newValue, JSON.parse(newValue))
        let value = JSON.parse(newValue) as dataItem
        visitCountData.value.push(value)
        if (visitCountData.value.length > 120) {
          visitCountData.value.splice(0, 110)
        }
        area.changeData(visitCountData.value)
      }
  );
  // g2plot
  const area = new Area('container', {
    data: visitCountData.value,
    xField: 'time',
    yField: 'count',
    smooth: true,
    xAxis: {
      range: [0, 1],
    },
    areaStyle: () => {
      return {
        fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
      };
    },
  });
  area.render();

});


</script>
